<template>
  <div class="container">
    <h3>vue+openlayers: select-modify-snap功能展示</h3>
    <div id="vue-openlayers"></div>
  </div>
</template>

<script>
import 'ol/ol.css'
import { Map, View } from 'ol'
import SourceVector from 'ol/source/Vector' // 矢量数据源
import LayerVector from 'ol/layer/Vector' // 矢量图层
import GeoJSON from 'ol/format/GeoJSON' // GeoJSON格式
import { Tile } from 'ol/layer' // 瓦片图层
import XYZ from 'ol/source/XYZ' // 瓦片数据源
import { formLonLat, fromLonLat } from 'ol/proj' // 坐标转换
import { Draw, Modify, Snap, Select } from 'ol/interaction' // 交互 绘制、修改、捕捉、选择

import CN from '../../assets/data/MapOfChina.json' // 中国地图数据
export default {
  data() {
    return {
      map: null,
      source: new SourceVector({ // 矢量数据源
        features: new GeoJSON().readFeatures(CN, { // 读取中国地图数据
          dataProjection: 'EPSG:4326', // 数据投影
          featureProjection: 'EPSG:3857' // 默认投影
        })
      }),
      view: new View({
        projection: 'EPSG:3857', // 投影
        center: fromLonLat([116.397411, 39.909186]), // 中心点 中国
        zoom: 3 // 缩放
      })
    }
  },
  mounted() {
    this.initMap()
  },
  methods: {
    initMap() {
      this.map = new Map({
        target: 'vue-openlayers',
        layers: [
          new Tile({
            source: new XYZ({
              url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=7'
            })
          }),
          new LayerVector({
            source: this.source
          })
        ],
        view: this.view
      })
      const select = new Select() // 选择
      const modify = new Modify({
        features: select.getFeatures() // 修改 选择的要素
      })
      const snap = new Snap({ // 捕捉
        source: this.source
      })
      this.map.addInteraction(select)
      this.map.addInteraction(modify)
      this.map.addInteraction(snap)
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
    width: 840px;
    height: 550px;
    margin: 50px auto;
    border: 1px solid #ccc;
    #vue-openlayers {
      width: 800px;
      height: 420px;
      margin: 0 auto;
      border: 1px solid #42b983;
      position: relative;
    }
  }
</style>